<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车票管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        #app {
            display: flex;
            min-height: 100vh;
            width: 100%;
        }

        .status-active {
            color: #43a047;
            font-weight: 500;
        }

        .status-inactive {
            color: #e53935;
            font-weight: 500;
        }

        .status-soldout {
            color: #ff9800;
            font-weight: 500;
        }

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .modal {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 700px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
        }

        .close-btn:hover {
            background-color: #f5f5f5;
        }

        .required {
            color: #e53935;
        }

        .no-data {
            text-align: center;
            padding: 40px 0;
            color: #999;
        }
    </style>
</head>
<body>

<div id="app">
    <!-- 主内容区 -->
    <div class="main-content">


        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">车票查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="trainNumber">车次号</label>
                            <input type="text" v-model="searchForm.trainNumber" class="form-control"
                                   placeholder="请输入车次号">
                        </div>
                        <div class="form-group col-3">
                            <label for="startStation">出发站</label>
                            <select v-model="searchForm.startStationId" class="form-control">
                                <option value="">全部</option>
                                <option v-for="station in stationList" :key="station.stationId"
                                        :value="station.stationId">
                                    {{ station.stationName }}
                                </option>
                            </select>
                        </div>
                        <div class="form-group col-3">
                            <label for="endStation">到达站</label>
                            <select v-model="searchForm.endStationId" class="form-control">
                                <option value="">全部</option>
                                <option v-for="station in stationList" :key="station.stationId"
                                        :value="station.stationId">
                                    {{ station.stationName }}
                                </option>
                            </select>
                        </div>
                        <div class="form-group col-3">
                            <label for="status">状态</label>
                            <select v-model="searchForm.status" class="form-control">
                                <option value="">全部</option>
                                <option value="1">可售</option>
                                <option value="0">停售</option>
                                <option value="2">售罄</option>
                            </select>
                        </div>
                        <div class="form-group col-12" style="margin-top: 20px;">
                            <button type="submit" class="btn btn-primary" style="margin-right: 10px;">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" class="btn btn-success" @click="openModal('添加车票')">
                                <i class="fas fa-plus"></i> 添加车票
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 车票列表 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">车票列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table>
                            <thead>
                            <tr>
                                <th>车票ID</th>
                                <th>车次号</th>
                                <th>出发站</th>
                                <th>到达站</th>
                                <th>出发时间</th>
                                <th>到达时间</th>
                                <th>票价</th>
                                <th>余票</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.ticketId">
                                <td>{{ item.ticketId }}</td>
                                <td>{{ item.trainNumberId }}</td>
                                <td>{{ getStationName(item.startStationId) }}</td>
                                <td>{{ getStationName(item.arrivalStationId) }}</td>
                                <td>{{ formatDateTime(item.departureTime) }}</td>
                                <td>{{ formatDateTime(item.arrivalTime) }}</td>
                                <td>¥{{ item.ticketPrice }}</td>
                                <td>{{ item.remainingTickets }}</td>
                                <td>
                                    <span v-if="item.ticketStatus === 1" class="status-active">可售</span>
                                    <span v-else-if="item.ticketStatus === 0" class="status-inactive">停售</span>
                                    <span v-else class="status-soldout">售罄</span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="btn btn-sm btn-primary" @click="handleEdit(item)">
                                            <i class="fas fa-edit"></i> 编辑
                                        </button>
                                        <button class="btn btn-sm btn-danger" @click="handleDelete(item.ticketId)">
                                            <i class="fas fa-trash"></i> 删除
                                        </button>
                                        <button class="btn btn-sm" :class="getButtonClass(item.ticketStatus)"
                                                @click="handleStatusChange(item.ticketId, item.ticketStatus)">
                                            <i class="fas" :class="getStatusIcon(item.ticketStatus)"></i>
                                            {{ getStatusAction(item.ticketStatus) }}
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <!-- 无数据提示 -->
                        <div v-if="tableData.length === 0" class="no-data">
                            <p>暂无数据</p>
                        </div>
                    </div>

                    <!-- 分页控件 -->
                    <div class="pagination" v-if="totalItems > 0"
                         style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;
                        </button>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="isModalVisible" class="modal-overlay" @click.self="closeModal">
        <div class="modal">
            <div class="modal-header">
                <h3>{{ currentModalTitle }}</h3>
                <button class="close-btn" @click="closeModal">&times;</button>
            </div>
            <div class="modal-body">
                <form class="form-row">
                    <div class="form-group col-6">
                        <label for="editTrainNumber">车次号 <span class="required">*</span></label>
                        <select class="form-control" id="editTrainNumber" v-model="formData.trainNumberId" required
                                @change="onTrainNumberChange">
                            <option value="">请选择车次</option>
                            <option v-for="train in trainList" :key="train.id" :value="train.id">
                                {{ train.id }}
                            </option>
                        </select>
                    </div>

                    <div class="form-group col-6">
                        <label for="editCarriageType">车厢类型 <span class="required">*</span></label>
                        <select class="form-control" id="editCarriageType" v-model="formData.carriageType" required>
                            <option value="">请选择车厢类型</option>
                            <option v-for="type in carriageTypeList" :key="type.carriageTypeId"
                                    :value="type.carriageTypeId">
                                {{ type.carriageTypeName }}
                            </option>
                        </select>
                    </div>

                    <div class="form-group col-6">
                        <label for="editStartStationId">出发站 <span class="required">*</span></label>
                        <select class="form-control" id="editStartStationId" v-model="formData.startStationId"
                                required :disabled="isTrainSelected">
                            <option value="">请选择出发站</option>
                            <option v-for="station in stationList" :key="station.stationId"
                                    :value="station.stationId">
                                {{ station.stationName }}
                            </option>
                        </select>
                    </div>

                    <div class="form-group col-6">
                        <label for="editEndStationId">到达站 <span class="required">*</span></label>
                        <select class="form-control" id="editEndStationId" v-model="formData.arrivalStationId"
                                required :disabled="isTrainSelected">
                            <option value="">请选择到达站</option>
                            <option v-for="station in stationList" :key="station.stationId"
                                    :value="station.stationId">
                                {{ station.stationName }}
                            </option>
                        </select>
                    </div>

                    <div class="form-group col-6">
                        <label for="editDepartureTime">出发时间 <span class="required">*</span></label>
                        <input type="datetime-local" class="form-control" id="editDepartureTime"
                               v-model="formData.departureTime" required :disabled="isTrainSelected">
                    </div>

                    <div class="form-group col-6">
                        <label for="editArrivalTime">到达时间 <span class="required">*</span></label>
                        <input type="datetime-local" class="form-control" id="editArrivalTime"
                               v-model="formData.arrivalTime" required :disabled="isTrainSelected">
                    </div>

                    <!-- 删除票价字段 -->
                    <div class="form-group col-6">
                        <label for="editTotalTickets">总票数 <span class="required">*</span></label>
                        <input type="number" class="form-control" id="editTotalTickets"
                               v-model="formData.totalTickets"
                               placeholder="请输入总票数" min="0" required
                               :disabled="isTrainSelected">
                    </div>
                    <div class="form-group col-6">
                        <label for="editRemainingTickets">余票</label>
                        <input type="number" class="form-control" id="editRemainingTickets"
                               v-model="formData.remainingTickets"
                               placeholder="请输入余票" min="0" required
                               :disabled="isTrainSelected">
                    </div>
                    <div class="form-group col-6">
                        <label for="editStatus">状态</label>
                        <select class="form-control" id="editStatus" v-model="formData.ticketStatus">
                            <option value="1" selected>可售</option>
                            <option value="0">停售</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" @click="closeModal">取消</button>
                <button class="btn btn-primary" @click="saveData">保存</button>
            </div>
        </div>
    </div>
</div>
</body>

<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>
<script>
    // 在data部分添加isTrainSelected标志
    new Vue({
        el: '#app',
        data: {
            searchForm: {
                trainNumber: '',
                startStationId: '',
                endStationId: '',
                status: ''
            },
            tableData: [],
            stationList: [],
            trainList: [],
            carriageTypeList: [], // 新增：存储车厢类型列表
            formData: {
                ticketId: '',
                trainNumberId: '', // 改为trainNumberId
                carriageType: 2, // 默认二等座
                startStationId: '',
                arrivalStationId: '',
                departureTime: '',
                arrivalTime: '',
                // 删除ticketPrice字段
                totalTickets: 0,
                remainingTickets: 0,
                ticketStatus: 0
            },
            isModalVisible: false,
            currentModalTitle: '',
            userName: '',
            // 分页相关数据
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            useFrontendPagination: false,
            isTrainSelected: false, // 新增：标记是否已选择车次
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },
            // 当前页显示的数据
            paginatedData() {
                return this.tableData;
            },
            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码
                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }
                return pages;
            },
            // 新增：开始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },
            // 新增：结束索引
            endIndex() {
                return Math.min(this.startIndex + this.pageSize, this.totalItems);
            }
        },
        methods: {
            // 新增：车次选择变化时的处理方法
            onTrainNumberChange() {
                if (this.formData.trainNumberId) {
                    this.fetchTrainDetails(this.formData.trainNumberId);
                } else {
                    this.isTrainSelected = false; // 清除选择时恢复编辑状态
                }
            },
            // 新增：获取车次详情的方法
            fetchTrainDetails(trainNumberId) {
                // 这里需要根据实际的API路径进行调整
                axios.get(`/admin/train_number/getDetail/${trainNumberId}`)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            const trainDetail = resp.data.data;

                            // 修复：根据车站名称查找对应的车站ID
                            this.formData.startStationId = this.getStationIdByName(trainDetail.startStation);
                            this.formData.arrivalStationId = this.getStationIdByName(trainDetail.endStation);

                            // 修复：字段名称映射 - startTime -> departureTime, arriveTime -> arrivalTime
                            // 格式化日期时间为datetime-local所需格式
                            const formatDateTimeLocal = (dateTime) => {
                                if (!dateTime) return '';
                                const date = new Date(dateTime);
                                return date.toISOString().slice(0, 16);
                            };

                            this.formData.departureTime = formatDateTimeLocal(trainDetail.startTime);
                            this.formData.arrivalTime = formatDateTimeLocal(trainDetail.arriveTime);

                            console.log('成功获取并设置车次详情:', {trainDetail, formData: this.formData});

                            // 新增：获取票数信息
                            return this.fetchTicketNumber(trainNumberId);
                        } else {
                            console.error('获取车次详情失败:', resp.data.message);
                            alert('获取车次详情失败，请重试');
                        }
                    })
                    .catch(error => {
                        console.error('获取车次详情请求失败:', error);
                        alert('获取车次详情失败，请重试');
                    });
            },

            // 新增：根据车次ID获取票数信息的方法
            fetchTicketNumber(trainNumberId) {
                var carriageType = this.formData.carriageType;
                axios.get(`/admin/train_number/getTicketNumber/${trainNumberId}/${carriageType}`)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            const ticketNumber = resp.data.data;

                            // 回填总票数和余票数
                            this.formData.totalTickets = ticketNumber.allNumbers || 0;
                            this.formData.remainingTickets = ticketNumber.remainNumbers || 0;

                            // 禁用字段（包括票数字段）
                            this.isTrainSelected = true;

                            console.log('成功获取并设置票数信息:', {ticketNumber, formData: this.formData});
                        } else {
                            console.error('获取票数信息失败:', resp.data.message);
                            alert('获取票数信息失败，请重试');

                            // 即使获取票数失败，也禁用字段以防止手动输入
                            this.isTrainSelected = true;
                        }
                    })
                    .catch(error => {
                        console.error('获取票数信息请求失败:', error);
                        alert('获取票数信息失败，请重试');

                        // 即使获取票数失败，也禁用字段以防止手动输入
                        this.isTrainSelected = true;
                    });
            },
            search() {
                this.currentPage = 1; // 搜索时重置到第一页
                this.loadData();
            },
            openModal(title, isEdit = false) {
                this.currentModalTitle = title;
                if (!isEdit) {
                    this.resetForm(); // 只有在非编辑模式下才重置表单
                }
                this.isModalVisible = true;
            },
            closeModal() {
                this.isModalVisible = false;
                this.resetForm();
            },
            // 修改resetForm方法，重置isTrainSelected标志
            resetForm() {
                this.formData = {
                    ticketId: '',
                    trainNumberId: '',
                    carriageType: 2, // 默认二等座
                    startStationId: '',
                    arrivalStationId: '',
                    departureTime: '',
                    arrivalTime: '',
                    totalTickets: 0,
                    remainingTickets: 0,
                    ticketStatus: 0
                };
                this.isTrainSelected = false; // 重置为可编辑状态
            },

            // 修改handleEdit方法，添加编辑时自动禁用字段的逻辑
            handleEdit(item) {
                // 转换日期时间格式为datetime-local所需的格式
                const formatDateTimeLocal = (dateTime) => {
                    if (!dateTime) return '';
                    const date = new Date(dateTime);
                    return date.toISOString().slice(0, 16);
                };

                this.formData = {
                    ticketId: item.ticketId,
                    trainNumberId: item.trainNumberId,
                    carriageType: item.carriageType || 2,
                    startStationId: item.startStationId,
                    arrivalStationId: item.arrivalStationId,
                    departureTime: formatDateTimeLocal(item.departureTime),
                    arrivalTime: formatDateTimeLocal(item.arrivalTime),
                    ticketPrice: item.ticketPrice || 0,
                    totalTickets: item.totalTickets || 0,
                    remainingTickets: item.remainingTickets || 0,
                    ticketStatus: item.ticketStatus || 0
                };

                // 编辑模式下，如果有车次号，也应该禁用相关字段
                this.isTrainSelected = !!item.trainNumberId;

                this.openModal('编辑车票', true); // 传递true表示编辑模式
            },
            handleDelete(ticketId) {
                if (confirm('确定要删除该车票吗？删除后数据将无法恢复！')) {
                    axios.delete(`/admin/ticket_manage/delete/${ticketId}`)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('删除成功');
                                this.loadData(); // 重新加载数据
                            } else {
                                alert('删除失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('删除请求失败:', error);
                            alert('删除失败，请重试');
                        });
                }
            },
            handleStatusChange(ticket_id, ticket_status) {
                let newStatus;
                let action;

                if (ticket_status === 1) {
                    newStatus = 0;
                    action = '停售';
                } else {
                    newStatus = 1;
                    action = '开售';
                }

                if (confirm(`确定要${action}该车票吗？`)) {
                    axios.post('/admin/ticket_manage/changeStatus', {
                        ticketId: ticket_id,
                        ticketStatus: newStatus
                    })
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert(`${action}成功`);
                                this.loadData(); // 重新加载数据
                            } else {
                                alert(`${action}失败: ` + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error(`${action}请求失败:`, error);
                            alert(`${action}失败，请重试`);
                        });
                }
            },
            saveData() {
                // 表单验证
                if (!this.formData.trainNumberId) {
                    alert('请选择车次号');
                    return;
                }
                if (!this.formData.startStationId) {
                    alert('请选择出发站');
                    return;
                }
                if (!this.formData.arrivalStationId) {
                    alert('请选择到达站');
                    return;
                }
                if (!this.formData.departureTime) {
                    alert('请选择出发时间');
                    return;
                }
                if (!this.formData.arrivalTime) {
                    alert('请选择到达时间');
                    return;
                }
                // 删除票价验证
                if (this.formData.totalTickets < 0) {
                    alert('请输入有效的总票数');
                    return;
                }
                if (this.formData.remainingTickets < 0) {
                    alert('请输入有效的余票数');
                    return;
                }
                if (this.formData.remainingTickets > this.formData.totalTickets) {
                    alert('余票数不能大于总票数');
                    return;
                }
                if (new Date(this.formData.departureTime) >= new Date(this.formData.arrivalTime)) {
                    alert('出发时间不能晚于到达时间');
                    return;
                }

                const url = this.formData.ticketId ? '/admin/ticket_manage/update' : '/admin/ticket_manage/add';
                const submitData = {...this.formData};

                axios.post(url, submitData)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert(this.formData.ticketId ? '编辑成功' : '添加成功');
                            this.closeModal();
                            this.loadData(); // 重新加载数据
                        } else {
                            alert(this.formData.ticketId ? '编辑失败: ' : '添加失败: ' + resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('保存请求失败:', error);
                        alert('操作失败，请重试');
                    });
            },
            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                this.currentPage = page;
                this.loadData();
            },

            loadData() {
                axios.get("/admin/ticket_manage/getList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        trainNumber: this.searchForm.trainNumber || null,
                        startStationId: this.searchForm.startStationId || null,
                        arrivalStationId: this.searchForm.endStationId || null,
                        ticketStatus: this.searchForm.status || null
                    }
                })
                    .then(resp => {
                        if (resp.data.code === 200) {
                            this.tableData = resp.data.data.list || [];
                            this.totalItems = resp.data.data.total || 0;
                        } else {
                            alert("加载数据失败: " + resp.message);
                            this.tableData = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error('加载数据失败:', error);
                        alert('加载数据失败，请重试');
                    });
            },

            mounted() {
                // 修复加载时序，先加载车站、车次和车厢类型列表，再加载车票列表
                // 加载车站列表
                this.loadStations().then(() => {
                    // 加载车次列表
                    return this.loadTrains();
                }).then(() => {
                    // 加载车厢类型列表
                    return this.loadCarriageTypes();
                }).then(() => {
                    // 确保数据加载完成后再加载车票列表
                    setTimeout(() => {
                        this.loadData();
                    }, 300);
                });

                // 设置当前页面标识
                sessionStorage.setItem('currentPage', 'ticket_manage.html');
            },

            // 修改loadStations方法返回Promise，便于控制加载顺序
            loadStations() {
                return new Promise((resolve, reject) => {
                    axios.get("/admin/train_number/findStationList")
                        .then(resp => {
                            if (resp.data.code === 200) {
                                this.stationList = resp.data.data || [];
                                console.log('成功加载车站列表:', this.stationList);
                            } else {
                                alert("加载车站列表失败: " + resp.message);
                                this.stationList = [];
                            }
                            resolve();
                        })
                        .catch(error => {
                            console.error('加载车站列表失败:', error);
                            reject(error);
                        });
                });
            },

            // 类似地修改loadTrains和loadCarriageTypes方法返回Promise
            loadTrains() {
                return new Promise((resolve, reject) => {
                    axios.get("/admin/train_number/getAllTrainNumbers")
                        .then(resp => {
                            if (resp.data.code === 200) {
                                this.trainList = resp.data.data || [];
                            } else {
                                alert("加载车次列表失败: " + resp.message);
                                this.trainList = [];
                            }
                            resolve();
                        })
                        .catch(error => {
                            console.error('加载车次列表失败:', error);
                            reject(error);
                        });
                });
            },

            loadCarriageTypes() {
                return new Promise((resolve, reject) => {
                    axios.get("/admin/train_carriage_manage/getCarriageTypes")
                        .then(resp => {
                            if (resp.data.code === 200) {
                                this.carriageTypeList = [
                                    {carriageTypeId: 1, carriageTypeName: '一等座'},
                                    {carriageTypeId: 2, carriageTypeName: '二等座'},
                                    {carriageTypeId: 3, carriageTypeName: '商务座'},
                                    {carriageTypeId: 4, carriageTypeName: '硬座'},
                                    {carriageTypeId: 5, carriageTypeName: '硬卧'},
                                    {carriageTypeId: 6, carriageTypeName: '软卧'}
                                ];
                            } else {
                                alert("加载车厢类型失败: " + resp.message);
                                this.carriageTypeList = [
                                    {carriageTypeId: 1, carriageTypeName: '一等座'},
                                    {carriageTypeId: 2, carriageTypeName: '二等座'},
                                    {carriageTypeId: 3, carriageTypeName: '商务座'},
                                    {carriageTypeId: 4, carriageTypeName: '硬座'},
                                    {carriageTypeId: 5, carriageTypeName: '硬卧'},
                                    {carriageTypeId: 6, carriageTypeName: '软卧'}
                                ];
                            }
                            resolve();
                        })
                        .catch(error => {
                            console.error('加载车厢类型失败:', error);
                            this.carriageTypeList = [
                                {carriageTypeId: 1, carriageTypeName: '一等座'},
                                {carriageTypeId: 2, carriageTypeName: '二等座'},
                                {carriageTypeId: 3, carriageTypeName: '商务座'},
                                {carriageTypeId: 4, carriageTypeName: '硬座'},
                                {carriageTypeId: 5, carriageTypeName: '硬卧'},
                                {carriageTypeId: 6, carriageTypeName: '软卧'}
                            ];
                            resolve(); // 即使出错也继续
                        });
                });
            },
            formatDateTime(dateTime) {
                if (!dateTime) return '';
                const date = new Date(dateTime);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}`;
            },

            getStationName(stationId) {
                // 简化方法，只匹配stationId字段，确保类型转换正确
                if (!stationId) return '';
                const numId = Number(stationId);
                const station = this.stationList.find(s => Number(s.stationId) === numId);
                return station ? station.stationName : `[未找到:${stationId}]`;
            },
            // 在Vue实例的methods部分，getStationName函数旁边添加以下代码
            getStationIdByName(stationName) {
                if (!stationName) return '';
                // 遍历车站列表，查找匹配的车站名称
                const station = this.stationList.find(s => s.stationName === stationName);
                return station ? station.stationId : '';
            },

            getButtonClass(ticketStatus) {
                if (ticketStatus === 1) return 'btn-info'; // 天蓝色
                return 'btn-success';
            },

            getStatusIcon(ticketStatus) {
                if (ticketStatus === 1) return 'fa-pause';
                return 'fa-play';
            },

            getStatusAction(ticketStatus) {
                if (ticketStatus === 1) return '停售';
                return '开售';
            }
        },
        mounted() {
            // 修复加载时序，先加载车站、车次和车厢类型列表，再加载车票列表
            // 加载车站列表
            this.loadStations().then(() => {
                // 加载车次列表
                return this.loadTrains();
            }).then(() => {
                // 加载车厢类型列表
                return this.loadCarriageTypes();
            }).then(() => {
                // 确保数据加载完成后再加载车票列表
                setTimeout(() => {
                    this.loadData();
                }, 300);
            });

            // 设置当前页面标识
            sessionStorage.setItem('currentPage', 'ticket_manage.html');
        }
    });
</script>
</html>
